package com.tanhua.server.service;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.enums.SexEnum;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.service.PicUploadService;
import com.tanhua.server.utils.RelativeDateFormat;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.Movements;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.server.vo.VisitorsVo;
import net.sf.jsqlparser.expression.LongValue;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class MovementsService {

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;


    /**
     * 发布动态
     * @param textContent 文字动态
     * @param location 位置
     * @param latitude 经度
     * @param longitude 纬度
     * @param multipartFile 图片(支持多张)
     * @return publish.getId()
     */
    public String savePublish(String textContent,
                               String location,
                               String latitude,
                               String longitude,
                               MultipartFile[] multipartFile) {

        //查询当前的登录信息
        User user = UserThreadLocal.get();

        //封装Publish动态对象
        Publish publish = new Publish();
        publish.setUserId(user.getId());
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLatitude(latitude);
        publish.setLongitude(longitude);
        publish.setSeeType(1);//谁可以看(1-公开,2-私密,3-部分可见,4-不给谁看)

        List<String> picUrls = new ArrayList<>();
        //将传过来的图片上传到阿里云
        for (MultipartFile file : multipartFile) {
            //调用上传图片方法
            PicUploadResult picUploadResult = this.picUploadService.upload(file);
            //获取图片(阿里云的图片路径)
            picUrls.add(picUploadResult.getName());
        }

        //将图片集合封装到动态对象中
        publish.setMedias(picUrls);
        return this.quanZiApi.savePublish(publish);
    }

    /**
     * 根据类型查询动态
     * @param page 页码
     * @param pageSize 每页显示数量
     * @param isRecommend 是否是推荐
     * @return
     */
    private PageResult queryPublishList(Integer page, Integer pageSize,boolean isRecommend) {
        PageResult pageResult = new PageResult();
        //获取当前的登录信息
        User user = UserThreadLocal.get();

        PageInfo<Publish> pageInfo = null;
        if (isRecommend) { //推荐动态逻辑处理
            // 查询Redis
            String value = this.redisTemplate.opsForValue().get("QUANZI_PUBLISH_RECOMMEND_" + user.getId());
            //判断是否为空
            if (StringUtils.isNotEmpty(value)) {
                //不为空则代表redis中有推荐的值
                //分割,得到pid数组
                String[] pids = StringUtils.split(value, ',');
                int startIndex = (page - 1) * pageSize;
                //开始索引要小于总数据
                if(startIndex < pids.length){
                    //结束索引=开始索引+每页显示数量-1
                    int endIndex = startIndex + pageSize - 1;
                    //结束索引同样要小于总数据,否则设置最后的为数组最后一个数据
                    if (endIndex >= pids.length) {
                        endIndex = pids.length - 1;
                    }

                    //将数组中pid存入集合中
                    List<Long> pidList = new ArrayList<>();
                    for (int i = startIndex; i <= endIndex; i++) {
                        pidList.add(Long.valueOf(pids[i]));
                    }

                    //获取publish集合
                    List<Publish> publishList = this.quanZiApi.queryPublishByPids(pidList);
                    pageInfo = new PageInfo<>();
                    pageInfo.setRecords(publishList);
                }
            }
        }

        //当pageInfo为空代表查的是好友动态列表
        if (null == pageInfo) {
            Long userId = isRecommend ? null : user.getId();
            pageInfo = this.quanZiApi.queryPublishList(pageSize, page, userId);
        }

        if (pageInfo.getRecords().size()==0){
            pageInfo=this.quanZiApi.queryPublishList(pageSize,page,null);
        }

        pageResult.setPagesize(pageSize);
        pageResult.setPage(page);
        pageResult.setCounts(0);
        pageResult.setPages(0);

        List<Publish> records = pageInfo.getRecords();

        //当返回值的数据为空,代表没有动态数据
        if (CollectionUtils.isEmpty(records)) {
            //没有动态信息,直接返回false
            return pageResult;
        }

        //遍历动态,将数据封装到Movements单条动态中,并将对象存入集合
        List<Movements> movementsList = new ArrayList<>();
        for (Publish record : records) {
            Movements movements = new Movements();

            movements.setId(record.getId().toHexString());
            movements.setImageContent(record.getMedias().toArray(new String[]{}));
            movements.setTextContent(record.getText());
            movements.setUserId(record.getUserId());
            movements.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated())));

            movementsList.add(movements);
        }

        //遍历单个动态集合获取他的userId存入userIds中
        List<Long> userIds = new ArrayList<>();
        for (Movements movements : movementsList) {
            //判断userID中是否包含遍历得到的userID
            if(!userIds.contains(movements.getUserId())){
                userIds.add(movements.getUserId());
            }

        }

        //查找mysql数据库的所有id=集合的userInfo对象集合
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(queryWrapper);
        //遍历Movements 和 UserInfo对象  给单个动态封装
        for (Movements movements : movementsList) {
            for (UserInfo userInfo : userInfos) {
                //判断两个对象的userID知否相等,在封装
                if (movements.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    movements.setAge(userInfo.getAge());
                    movements.setAvatar(userInfo.getLogo());
                    movements.setGender(userInfo.getSex().name().toLowerCase());
                    movements.setNickname(userInfo.getNickName());
                    movements.setTags(StringUtils.split(userInfo.getTags(), ','));


                    //查询评论数type:2
                    Long commentCount = this.quanZiApi.queryCommentCount(movements.getId(), 2);
                    if(null == commentCount){
                        //如果评论数为空则将评论数设置为0
                        movements.setCommentCount(0); //评论数
                    }else{
                        //否则将评论数设置为查出来的
                        movements.setCommentCount(commentCount.intValue()); //评论数
                    }


//                    movements.setCommentCount(10); //TODO 评论数
                    movements.setDistance("1.2公里"); //TODO 距离

                    //根据userKey从redis中获取数据(user,getId()-当前登录用户id   movements.getId()-动态用户的id  )
                    String userKey="QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + movements.getId();
                    //有数据返回true,没有返回false
                    movements.setHasLiked(this.redisTemplate.hasKey(userKey)?1:0); //是否点赞（1是，0否）

                    //movements.setHasLoved(0); //TODO 是否喜欢（1是，0否）
                    //根据user1Key从redis中获取数据(user,getId()-当前登录用户id   movements.getId()-动态用户的id  )
                    String user1Key="QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + movements.getId();
                    //有数据返回true,没有返回false
                    movements.setHasLoved(this.redisTemplate.hasKey(user1Key)?1:0); //是否喜欢（1是，0否）

                    String likeKey="QUANZI_COMMENT_LIKE_" + movements.getId();
                    String likeValue =this.redisTemplate.opsForValue().get(likeKey);
                    if (StringUtils.isNotEmpty(likeValue)){
                        movements.setLikeCount(Integer.valueOf(likeValue)); //点赞数
                    }else{
                        movements.setLikeCount(0); //TODO 点赞数
                    }

                    String loveKey="QUANZI_COMMENT_LOVE_" + movements.getId();
                    String loveValue =this.redisTemplate.opsForValue().get(loveKey);
                    if (StringUtils.isNotEmpty(loveValue)){
                        movements.setLoveCount(Integer.valueOf(loveValue)); //喜欢数
                    }else{
                        movements.setLoveCount(0); //TODO 喜欢数
                    }
                    //movements.setLoveCount(80); //TODO 喜欢数
                    break;
                }
            }
        }

        //将单个动态信息封装进分页结果对象中,并返回
        pageResult.setItems(movementsList);
        return pageResult;
    }

    /**
     *查询推荐动态
     * @param page
     * @param pageSize
     * @param isRecommend
     * @return
     */
    public PageResult queryRecommendPublishList(Integer page, Integer pageSize, boolean isRecommend) {
        return queryPublishList(page,pageSize,isRecommend);
    }

    /**
     * 查询好友动态
     * @param page 页码
     * @param pageSize 每页数量
     * @param isRecommend 是否是推荐动态
     * @return
     */
    public PageResult queryUserPublishList(Integer page, Integer pageSize, boolean isRecommend) {
        return this.queryPublishList(page,pageSize,isRecommend);
    }


    /**
     * 点赞
     *
     * @param publishId 动态或视频id
     * @return 点赞总数
     */
    public Long likeComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean bool = this.quanZiApi.saveLikeComment(user.getId(), publishId);
        if (!bool) {
            //不成功则传一个null
           return null;
        }

        Long likeCount = 0L;

        //保存点赞数到redis
        String key = "QUANZI_COMMENT_LIKE_" + publishId;
        //先判断redis里有没有这个Key
        if (!this.redisTemplate.hasKey(key)) {
            //没有则根据发布id和类型(1:点赞)执行queryCommentCount方法去查找mongoDB中有多少条数据
            //因为上面已经将点赞信息保存到mongoDB中,所以不用加一
            Long count = this.quanZiApi.queryCommentCount(publishId, 1);
            likeCount = count;
            //保存到redis中
            this.redisTemplate.opsForValue().set(key, String.valueOf(likeCount));
        } else {
            //有key则用increment方法让redis中的数据加一
            likeCount = this.redisTemplate.opsForValue().increment(key);
        }

        //记录该用户已点赞
        String userKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + publishId;
        this.redisTemplate.opsForValue().set(userKey, "1");

        return likeCount;
    }

    /**
     * 取消点赞
     * @param publishId 动态id
     * @return 返回减一后的动态点赞数
     */
    public Long cancelLikeComment(String publishId) {
        User user = UserThreadLocal.get();
        //参数(1:点赞)
        boolean bool = this.quanZiApi.removeComment(user.getId(), publishId, 1);
        if (bool) {

            String key = "QUANZI_COMMENT_LIKE_" + publishId;
            //该动态点赞数减一
            Long likeCount = this.redisTemplate.opsForValue().decrement(key);

            //删除redis中记录的该用户对该动态的点赞记录
            String userKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + publishId;
            this.redisTemplate.delete(userKey);

            return likeCount;
        }
        return null;
    }


    /**
     * 喜欢
     *
     * @param publishId
     * @return
     */
    public Long loveComment(String publishId) {
        //获取该登录用户信息
        User user = UserThreadLocal.get();

        //喜欢成功点击则收到一个true
        boolean bool = this.quanZiApi.saveLoveComment(user.getId(), publishId);
        if (!bool) {
            //如果不成功则返回一个null
            return null;
        }
        //成功后
        Long loveCount = 0L;

        //保存喜欢数到redis
        String key = "QUANZI_COMMENT_LOVE_" + publishId;
        if (!this.redisTemplate.hasKey(key)) {
            //如果该键不存在则将喜欢数添加到redis中
            Long count = this.quanZiApi.queryCommentCount(publishId, 3);
            loveCount = count ;
            this.redisTemplate.opsForValue().set(key, String.valueOf(loveCount));
        } else {
            //否则将喜欢数加一
            loveCount = this.redisTemplate.opsForValue().increment(key);
        }

        //记录已喜欢
        String userKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + publishId;
        this.redisTemplate.opsForValue().set(userKey, "1");

        return loveCount;
    }

    /**
     * 取消喜欢
     *
     * @return
     */
    public Long cancelLoveComment(String publishId) {
        User user = UserThreadLocal.get();
        boolean bool = this.quanZiApi.removeComment(user.getId(), publishId, 3);
        if (bool) {
            String key = "QUANZI_COMMENT_LOVE_" + publishId;
            //喜欢数减一
            Long loveCount = this.redisTemplate.opsForValue().decrement(key);

            //删除已点赞
            String userKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + publishId;
            this.redisTemplate.delete(userKey);

            return loveCount;
        }
        return null;
    }

    /**
     * 查询单条动态
     * 1:先根据动态id查询发布的动态对象
     * 2:将单个动态对象需要的属性从动态对象中获取
     * @param publishId
     * @return Movements 单个动态
     */
    public Movements queryById(String publishId) {
        //返回动态对象
        Publish publish = this.quanZiApi.queryPublishById(publishId);
        //判断对象是否为空
        if (null == publish) {
            return null;
        }

        //创建单个对象对象
        Movements movements = new Movements();
        //将动态信息存入单个动态对象中
        //动态id->动态id
        movements.setId(publish.getId().toHexString());
        //动态媒体数据->图片动态
        movements.setImageContent(publish.getMedias().toArray(new String[]{}));
        //文字->文字动态
        movements.setTextContent(publish.getText());
        //用户id->用户id
        movements.setUserId(publish.getUserId());
        //发布时间->发布时间(例:十分钟前)   调用RelativeDateFormat的format方法
        movements.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
        //查询该动态的用户对象
        UserInfo userInfo = this.userInfoService.queryById(publish.getUserId());
        //判断是否为空
        if (null == userInfo) {
            return null;
        }
        //将单个动态对象和用户对象传过去,利用该方法继续封装单个动态对象
        this.fillValueToMovements(movements, userInfo);

        return movements;

    }

    /**
     * 1:获取user对象
     * 2:根据传来的userInfo对象将需要的属性传入单个动态对象中
     * 3:通过调用一系列方法获取剩下的属性
     * @param movements
     * @param userInfo
     */
    private void fillValueToMovements(Movements movements, UserInfo userInfo) {
        //将用户信息封装到单个动态对象中
        User user = UserThreadLocal.get();
        movements.setAge(userInfo.getAge());
        //头像
        movements.setAvatar(userInfo.getLogo());
        movements.setGender(userInfo.getSex().name().toLowerCase());
        movements.setNickname(userInfo.getNickName());
        //标签(,号区分这里用的数组储存,所以用,分割成数组)
        movements.setTags(StringUtils.split(userInfo.getTags(), ','));

        //查询评论数type:2
        Long commentCount = this.quanZiApi.queryCommentCount(movements.getId(), 2);
        if(null == commentCount){
            //如果评论数为空则将评论数设置为0
            movements.setCommentCount(0); //评论数
        }else{
            //否则将评论数设置为查出来的
            movements.setCommentCount(commentCount.intValue()); //评论数
        }

        movements.setDistance("1.2公里"); //TODO 距离

        //通过redis查是否点赞
        String userKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + movements.getId();
        movements.setHasLiked(this.redisTemplate.hasKey(userKey) ? 1 : 0); //是否点赞（1是，0否）

        //通过该动态的用户id查询点赞数封装到单个动态对象中
        String key = "QUANZI_COMMENT_LIKE_" + movements.getId();
        String value =this.redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotEmpty(value)) {
            movements.setLikeCount(Integer.valueOf(value)); //点赞数
        } else {
            movements.setLikeCount(0);
        }

        //通过redis查询该用户是否对该动态喜欢了
        String userLoveKey = "QUANZI_COMMENT_LOVE_USER_" + user.getId() + "_" + movements.getId();
        movements.setHasLoved(this.redisTemplate.hasKey(userLoveKey) ? 1 : 0); //是否喜欢（1是，0否）

        //通过该动态的用户id查询喜欢数封装到单个动态对象中
        key = "QUANZI_COMMENT_LOVE_" + movements.getId();
        value = this.redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotEmpty(value)) {
            movements.setLoveCount(Integer.valueOf(value)); //喜欢数
        } else {
            movements.setLoveCount(0);
        }
    }


    /**
     *谁看过我
     * @return 访问者对象集合
     */
    public List<VisitorsVo> queryVisitorsList() {
        User user = UserThreadLocal.get();
        String redisKey = "visitor_date_" + user.getId();

        // 如果redis中存在上次查询的时间，就按照这个时间之后查询，如果没有就查询前5个
        List<Visitors> visitors = null;
        String value = this.redisTemplate.opsForValue().get(redisKey);
        if(StringUtils.isEmpty(value)){
            visitors = this.visitorsApi.topVisitor(user.getId(), 5);
        }else{
            visitors = this.visitorsApi.topVisitor(user.getId(), Long.valueOf(value));
        }

        //当visitors为空,返回空集合
        if(CollectionUtils.isEmpty(visitors)){
            return Collections.emptyList();
        }

        //遍历访问者集合 将每个来访问的用户id添加到集合中
        List<Long> userIds = new ArrayList<>();
        for (Visitors visitor : visitors) {
            userIds.add(visitor.getVisitorUserId());
        }

        //调用方法  从数据库中获取所有访问者的用户信息集合
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);

        List<VisitorsVo> visitorsVoList = new ArrayList<>();

        //遍历访问者用户信息集合和用户集合,将属性封装到访问者对象中,并添加到集合中
        for (Visitors visitor : visitors) {
            for (UserInfo userInfo : userInfoList) {
                //访问者id需要和用户id相等才能封装
                if(visitor.getVisitorUserId().longValue() == userInfo.getUserId().longValue()){

                    VisitorsVo visitorsVo = new VisitorsVo();
                    visitorsVo.setAge(userInfo.getAge());
                    visitorsVo.setAvatar(userInfo.getLogo());
                    //枚举转为String
                    //SexEnum sex = userInfo.getSex(); ->获取枚举类封装的值-.转为小写
                    visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
                    visitorsVo.setId(userInfo.getUserId());
                    visitorsVo.setNickname(userInfo.getNickName());
                    visitorsVo.setTags(StringUtils.split(userInfo.getTags(), ','));
                    visitorsVo.setFateValue(visitor.getScore().intValue());

                    visitorsVoList.add(visitorsVo);
                    break;
                }
            }
        }

        return visitorsVoList;
    }

    /**
     * 查询相册
     * @param userId 用户id
     * @param page 页码
     * @param pageSize 每页数量
     * @return  分页结果对象
     */
    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setCounts(0);
        pageResult.setPages(0);

        //查询相册
        PageInfo<Publish> albumPageInfo = this.quanZiApi.queryAlbumList(userId, page, pageSize);
        List<Publish> records = albumPageInfo.getRecords();

        //如果查询结果为空,那么直接返回没有数据的分页结果对象
        if(CollectionUtils.isEmpty(records)){
            return pageResult;
        }

        //遍历动态集合 将数据封装到单条动态中 并封装到集合
        List<Movements> movementsList = new ArrayList<>();
        for (Publish record : records) {
            Movements movements = new Movements();

            movements.setId(record.getId().toHexString());
            movements.setImageContent(record.getMedias().toArray(new String[]{}));
            movements.setTextContent(record.getText());
            movements.setUserId(record.getUserId());
            movements.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated())));

            movementsList.add(movements);
        }

        //遍历单条动态对象集合,将每个单条动态的用户id添加到集合中
        List<Long> userIds = new ArrayList<>();
        for (Movements movements : movementsList) {
            if (!userIds.contains(movements.getUserId())) {
                userIds.add(movements.getUserId());
            }

        }

        //根据用户id 集合调用方法获取userInfo对象集合
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(queryWrapper);
        //遍历单条动态集合和userInfo对象集合  将用户信息封装到单条动态对象中   并存入集合
        for (Movements movements : movementsList) {
            for (UserInfo userInfo : userInfos) {
                if (movements.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    this.fillValueToMovements(movements, userInfo);
                    break;
                }
            }
        }

        //将集合赛到分页结果对象中,返回分页结果对象
        pageResult.setItems(movementsList);

        return pageResult;
    }
}
